package com.sxfq.loansupermarket.backsystem.modular.guest.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.MembersUser;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.MemberProductService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.FirstCustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ScoreDealInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerPublicService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.CaseInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.DoctorOperationInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.ToothSite;
import com.sxfq.loansupermarket.backsystem.modular.guest.entity.GuestRevisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.guest.entity.SearchGuestRevisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.guest.service.GuestService;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author fengshuonan
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
@RequestMapping("/guest")
public class GuestController extends BaseController {
    @Autowired
    GuestService service;

    @Autowired
    private MemberProductService memberProductService;

    @Autowired
    IReservationsService reservationsService;

    @Autowired
    ICustomerPublicService customerPublicService;

    @Autowired
    IConsultantService consultantService;

    @Autowired
    ICustomerService customerService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/guestDimension/";

    @RequestMapping("")
    public String doctor_schedule(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "guestDimension_interview.html";
    }

    @RequestMapping("/guestDimension_openChat")
    public String guestDimension_openChat(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("id", ShiroKit.getUser().getId());
        return PREFIX + "guestDimension_openChat.html";
    }

    @RequestMapping("/doNoClose")
    public String doNoClose(Model model) {
        return "/doNoClose.html";
    }

    @RequestMapping(value = "/to_openBileList/{reservationsId}/{tabId}")
    public String to_openBileLists(@PathVariable String reservationsId, @PathVariable String tabId, Model model) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        //到过的店
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsId + "' order by add_time desc";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String dealTables = "";
        String rechargeTables = "";
        String customerTables = "";
        String customerTablesd = "";
        List<Map<String, String>> deptList = new ArrayList<Map<String, String>>();
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsId + "' ";
                rechargeTables += "select document_number,deal_id,id2,recharge_people,operation_time,remarks from " + head + "recharge_info where reservations_id='" + reservationsId + "' ";
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + reservationsId + "' ";
                customerTablesd += "select id,appointment_pay_service,arrival_time,archiving,field_tc from " + head + "customer_info t where reservations_id='" + reservationsId + "' and arrival_time is not null";
            } else {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsId + "' union ";
                rechargeTables += "select document_number,deal_id,id2,recharge_people,operation_time,remarks from " + head + "recharge_info where reservations_id='" + reservationsId + "' union ";
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + reservationsId + "' union ";
                customerTablesd += "select id,appointment_pay_service,arrival_time,archiving,field_tc " +
                        "from " + head + "customer_info t where reservations_id='" + reservationsId + "' " +
                        "and arrival_time is not null union ";
            }
        }
        if (abbreviationList.size() == 0) {
            return "/doNoClose.html";
        }
        String tableName = abbreviationList.get(0) + "recharge_info";
        String customerTableName = abbreviationList.get(0) + "customer_info";
        CustomerInfo customerInfo = customerService.selectOneByReservationsId(reservationsId, customerTableName); //当前记录的患者信息
        String sqlresrvations = "select id from reservations_info where id='" + customerInfo.getReservationsId() + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlresrvations, ReservationsInfo.class);
        if (reservationsInfo == null) {
            reservationsService.insert(customerInfo);
        }
        //看诊详情
        List<ConsultantInfo> consultantInfoList = consultantService.getConsultantInfoList2(customerInfo.getReservationsId());
        for (ConsultantInfo info1 : consultantInfoList) {
            if (info1.getDiagnosisTime() != "" && info1.getDiagnosisTime() != null) {
                info1.setDiagnosisTimeOne(info1.getDiagnosisTime().substring(0, 10));
                info1.setDiagnosisTimeTwo(info1.getDiagnosisTime().substring(11, info1.getDiagnosisTime().length()));
            }
        }
        //成交记录 ,结账记录
        String tableName1 = tableHead + "deal_info";
        String sql = "select t1.id as id,t1.customer_id as customerId ,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus, t1.tc_name as tcName ,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.operation_time,19) as operationTime," +
                "sum(t1.service_actual_pay)+sum(t1.deposit_amount) as totleServiceActualPay," +
                "if((select sum(folding_pay) from " + tableName1 + " a where a.operation_time=t1.operation_time and a.operation_time=a.get_time) is null,0," +
                " (select sum(folding_pay) from " + tableName1 + " a where a.operation_time=t1.operation_time and a.operation_time=a.get_time)) as totleFoldingPay," +
                "(select sum(deduction_amount) from " + tableName1 + " a where a.operation_time=t1.operation_time and a.operation_time=a.get_time) as totaldeductionAmount," +
                "sum(t1.arrears) as totleArrears,group_concat(distinct t1.remarks) as remarks," +
                " t1.folding_pay as foldingPay,t1.pay_service as payService," +
                "t2.id as payServiceId,t2.department as department,t2.first_level_project as firstLevelProject,t1.arrears as arrears," +
                "group_concat(distinct t2.pay_service_name) as payServiceName, t2.pay_service_price_one as payServicePriceOne, t2.pay_service_price_two as payServicePriceTwo," +
                "left(t1.get_time,19) as getTime ," +
                " group_concat(distinct t1.doctor) as doctor,t1.orthodontic_number as orthodonticNumber " +
                " from " + tableName1 + " t1 left join " + ShiroKit.getUser().getPay_service_info() + " t2 on t1.pay_service_id=t2.id " +
                " where t1.reservations_id='" + customerInfo.getReservationsId() + "' and pay_service_id is not null and t1.deal_status='已结账' group by  operationTime order by operationTime desc";
        List<PayServicedInfo> payServiceInfoList = sqlMapper.selectList(sql, PayServicedInfo.class);
        //未结账记录
        String sqlno = "SELECT t1.id AS id,t1.customer_id AS customerId,t1.reservations_id AS reservationsId,t1.tc_name as tcName ,t1.outpatient_name AS outpatientName," +
                " t1.deal_status AS dealStatus, left(t1.get_time,19) as getTime,t1.operation_time as operationTime, sum(t1.service_actual_pay) as serviceActualPay, " +
                " GROUP_CONCAT(DISTINCT t1.remarks) AS remarks,GROUP_CONCAT(DISTINCT t1.doctor) AS doctor" +
                " FROM " + tableName1 + " t1 LEFT JOIN " + ShiroKit.getUser().getPay_service_info() + " t2 ON t1.pay_service_id=t2.id" +
                " WHERE t1.reservations_id='" + customerInfo.getReservationsId() + "' AND (t1.deal_status='已开单' or t1.deal_status='待审核') " +
                " group by t1.get_time order by t1.get_time desc ";
        List<PayServicedInfo> NoPayServiceInfoList = sqlMapper.selectList(sqlno, PayServicedInfo.class);
        String getTime = "";
        for (PayServicedInfo info : payServiceInfoList) {
            if (info != null) {
                if (info.getOperationTime() != "" && info.getOperationTime() != null) {
                    info.setOperationTimeOne(info.getOperationTime().substring(0, 10));
                    info.setOperationTimeTwo(info.getOperationTime().substring(11, info.getOperationTime().length()));
                }
                getTime = info.getGetTime();
            }
            if (StringUtil.isNotEmpty(info.getOrthodonticNumber())) {
                customerInfo.setOrthodonticNumber(info.getOrthodonticNumber());
            }
        }

        FirstCustomerInfo customerInfoFirst = customerService.selectOneByReservationsIdFirst(reservationsId, customerTablesd);  //首次到店患者信息
        //就诊记录
        String sql11 = "select * from (" + customerTables + ") t order by t.startTime desc";
        List<CustomerInfo> customerInfoList = sqlMapper.selectList(sql11, CustomerInfo.class);
        for (CustomerInfo infos : customerInfoList) {
            infos.setOutpatientName(ShiroKit.getUser().getOutpatientName());
            if (infos.getStartTime() != "" && infos.getStartTime() != null) {
                infos.setStartTimeOne(infos.getStartTime().substring(0, 10));
                infos.setStartTimeTwo(infos.getStartTime().substring(11, infos.getStartTime().length()));
            }
        }
        //账单记录
        Double totalServiceActualPay = 0.00;
        Double totalArrears = 0.00;
        String custDealSql = "select t1.id2 as id2," +
                "t1.reservations_id as reservationsId, " +
                "t1.outpatient_name as outpatientName," +
                "left(t1.operation_time,19) as operationTime," +
                "t1.deal_status as dealStatus," +
                "GROUP_CONCAT( distinct (t1.doctor)) as doctor,GROUP_CONCAT( distinct (t1.nurse)) as nurse," +
                "t1.tc_name as tcName," +
                "sum(t1.service_actual_pay+t1.arrears+t1.deduction_amount+t1.deposit_amount) AS foldingPay," +
                "sum(t1.service_actual_pay) as serviceActualPay," +
                "sum(t1.arrears) as arrears," +
                "sum(t1.deduction_amount) as deductionAmount," +
                "sum(t1.deposit_amount) as depositAmount," +
                "t1.remarks as  remarks,(select distinct(r1.document_number) from (" + rechargeTables + ") r1 where r1.deal_id=t1.id group by r1.deal_id) as documentNumber " +
                "from (" + dealTables + ") t1 where t1.deal_status='已结账' and  t1.reservations_id = '" + customerInfo.getReservationsId() + "' " +
                "group by t1.operation_time order by t1.operation_time desc";
        List<PayServicedInfo> custDealList = sqlMapper.selectList(custDealSql, PayServicedInfo.class);
        for (int i = 0; i < custDealList.size(); i++) {
            List<PayServicedInfo> dealList = getDealInfoList(custDealList.get(i).getOperationTime(), custDealList.get(i).getReservationsId());
            custDealList.get(i).setDealList(dealList);
            custDealList.get(i).setDocumentNumber(dealList.get(0).getDocumentNumber());
            totalServiceActualPay = totalServiceActualPay + custDealList.get(i).getServiceActualPay() + custDealList.get(i).getDepositAmount();
            totalArrears = totalArrears + custDealList.get(i).getArrears();
        }
        //支付记录
        String payDealSql = "select t.outpatient_name as outpatientName,left(t.get_time,19) as getTime,t.is_do as isDo,t.tc_name as tcName,t.deal_status as dealStatus,t2.recharge_people " +
                "as rechargePeople,sum(t.folding_pay) as foldingPay,sum(t.service_actual_pay) as serviceActualPay, sum(t.arrears) as arrears," +
                "(sum(t.folding_pay)+sum(t.arrears)) as tkfoldingPay,sum(t.deduction_amount) AS deductionAmount,sum(t.deposit_amount) as depositAmount," +   //退款=应收+欠费
                "t2.remarks as remarks from (" + dealTables + ") t left join (select b.id2 as id2, b.recharge_people as recharge_people, " +
                "b.operation_time as operation_time,b.remarks as remarks from (" + rechargeTables + ") b group by b.operation_time) t2 on t.get_time = t2.operation_time where " +
                "t.reservations_id='" + customerInfo.getReservationsId() + "' and t.deal_status = '已结账' group by t.get_time order by t.get_time desc;";
        List<PayServicedInfo> payDealList = sqlMapper.selectList(payDealSql, PayServicedInfo.class);
        Double totalPayDealActualPay = 0.00;
        Double totalPayDealArrears = 0.00;
        for (int i = 0; i < payDealList.size(); i++) {
            totalPayDealActualPay = BigDecimal.valueOf(totalPayDealActualPay).add(BigDecimal.valueOf(payDealList.get(i).getServiceActualPay())).doubleValue();
            totalPayDealActualPay = BigDecimal.valueOf(totalPayDealActualPay).add(BigDecimal.valueOf(payDealList.get(i).getDepositAmount())).doubleValue();
            totalPayDealArrears = BigDecimal.valueOf(totalPayDealArrears).add(BigDecimal.valueOf(payDealList.get(i).getArrears())).doubleValue();
        }
        //欠费记录
        String arrearsDealSql = "select * from (select t.id2 as id2,t.reservations_id as reservationsId,t.customer_id as customerId," +
                "t.deal_status as dealStatus,t.outpatient_name as outpatientName,t.remarks as remarks,left(t.operation_time,19) as operationTime," +
                "t.doctor as doctor,t.tc_name as tcName,t.nurse as nurse,sum(t.deposit_amount) AS depositAmount,sum(t.deduction_amount) AS deductionAmount,sum(t.folding_pay) as foldingPay,sum(t.service_actual_pay)+sum(t.deposit_amount) as serviceActualPay,sum(t.arrears) as arrears,group_concat(distinct t1.pay_service_name) as payServiceName " +
                "from (" + dealTables + ") t  left join " + ShiroKit.getUser().getPay_service_info() + " t1 on t.pay_service_id=t1.id where t.deal_status='已结账' group by t.operation_time ) t1 where t1.reservationsId = '" + customerInfo.getReservationsId() + "' and t1.arrears  >0 order by t1.operationTime desc;";
        List<PayServicedInfo> arrearsDealList = sqlMapper.selectList(arrearsDealSql, PayServicedInfo.class);
        Double totalArrearsAmount = 0.00;
        for (int i = 0; i < arrearsDealList.size(); i++) {
            totalArrearsAmount += arrearsDealList.get(i).getArrears();
        }
        //通过预约ID  执行记录
        String sqll = "select t1.id as id,t1.id2 as id2,t1.customer_id as customerId,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.operation_time,19) as operationTime,left(t3.recharge_time,19) as rechargeTime,t1.remarks as remarks," +
                " t1.arrears as arrears,t2.pay_service_name as payServiceName,t1.get_time as getTime from (" + dealTables + ") t1 left join " + ShiroKit.getUser().getPay_service_info() + " t2 on t1.pay_service_id=t2.id left join " + tableName + " t3 on t3.id2=t1.id2 " +
                " where t1.reservations_id='" + customerInfo.getReservationsId() + "' and  t1.deal_status ='已结账'  group by  operationTime order by operationTime desc";
        List<PayServicedInfo> payServiceInfoList1 = sqlMapper.selectList(sqll, PayServicedInfo.class);
        Double totleReceivable = 0.00;
        Double totleFoldingPay = 0.00;   //
        Double totleServiceActualPay = 0.00; //总实收
        Double accountArrears = 0.00;  //总欠款
        for (PayServicedInfo info : payServiceInfoList1) {
            if (info != null) {
                if (info.getPayServiceId() != null && info.getPayServiceId() != "") {
                    if (info.getFoldingPay() != null) {
                        totleFoldingPay += info.getFoldingPay();
                    }
                    //总实收
                    if (info.getServiceActualPay() != null) {
                        totleServiceActualPay += info.getServiceActualPay();
                    }
                    //总欠款
                    if (info.getArrears() != null) {
                        accountArrears += info.getArrears();
                    }
                    info.setTotleReceivable(totleReceivable);
                    info.setTotleFoldingPay(totleFoldingPay);
                    info.setTotleServiceActualPay(totleServiceActualPay);
                    info.setAccountArrears(accountArrears);
                }
                if (info.getOperationTime() != "" && info.getOperationTime() != null) {
                    info.setOperationTimeOne(info.getOperationTime().substring(0, 10));
                    info.setOperationTimeTwo(info.getOperationTime().substring(11, info.getOperationTime().length()));
                }
                if (info.getRechargeTime() != "" && info.getRechargeTime() != null) {
                    info.setRechargeTimeOne(info.getRechargeTime().substring(0, 10));
                    info.setRechargeTimeTwo(info.getRechargeTime().substring(11, info.getRechargeTime().length()));
                }
            }
        }
        //病例记录
        //1、先查询当前客户的所有病例记录
        String caseInfoSql = "select left(t1.finnally_time,19) as finnallyTime1,t1.* from case_info t1  " +
                "where t1.reservations_id='" + customerInfo.getReservationsId() + "'order by t1.finnally_time desc";
        List<CaseInfo> caseInfoList = sqlMapper.selectList(caseInfoSql, CaseInfo.class);
        for (CaseInfo infos : caseInfoList) {
            if (infos != null) {
                if (infos.getOperationTime() != "" && infos.getOperationTime() != null) {
                    infos.setOperationTime(infos.getOperationTime().substring(0, 10));
                }
                String sql3 = "select pay_service_name as payServiceName from " + ShiroKit.getUser().getPay_service_info() + " where id ='" + infos.getPayServiceId() + "'";
                CaseInfo caseInfo1 = sqlMapper.selectOne(sql3, CaseInfo.class);
                if (caseInfo1 == null) {
                    continue;
                }
                infos.setPayServiceName(caseInfo1.getPayServiceName());
            }
        }
        //2.循环遍历每个病例记录，给对应病例的牙位属性赋值
        for (CaseInfo caseInfo : caseInfoList) {
            //然后查询牙位集合
            String toothSIteSql = "select * from tooth_site t1 where t1.case_id='" + caseInfo.getId() + "' ";
            List<ToothSite> toothSiteList = sqlMapper.selectList(toothSIteSql, ToothSite.class);
            for (ToothSite toothSite : toothSiteList) {
                //根据对应的牙位类型，给病例实体的对应牙位属性赋值
                if (toothSite.getYaType().equals("1")) {
                    caseInfo.getToothSite1List().add(toothSite);
                }
                if (toothSite.getYaType().equals("2")) {
                    caseInfo.getToothSite2List().add(toothSite);
                }
                if (toothSite.getYaType().equals("3")) {
                    caseInfo.getToothSite3List().add(toothSite);
                }
                if (toothSite.getYaType().equals("4")) {
                    caseInfo.getToothSite4List().add(toothSite);
                }
                if (toothSite.getYaType().equals("5")) {
                    caseInfo.getToothSite5List().add(toothSite);
                }
            }
        }
        String selectsql = "select id from today_operation_info where reservations_id='" + customerInfo.getReservationsId() + "' and " +
                " left(operation_time,10)='" + DateTimeKit.now().substring(0, 10) + "' and operation_people='" + ShiroKit.getUser().getAccount() + "'" +
                " and store='" + customerInfo.getArrivalStore() + "'";
        List<DoctorOperationInfo> doctorOperationInfo = sqlMapper.selectList(selectsql, DoctorOperationInfo.class);
        if (doctorOperationInfo.size() == 0) { //是否操作过该患者
            //插入 今日操作数据 前台
            String insertSql = " INSERT INTO today_operation_info  (customer_id,reservations_id,szm,operation_people,customer_name, " +
                    " customer_sex,customer_age, customer_phone,store,operation_time) values  " +
                    " ('" + customerInfo.getId() + "','" + customerInfo.getReservationsId() + "','" + customerInfo.getSzm() + "','" + ShiroKit.getUser().getAccount() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerSex() + "', " +
                    " '" + customerInfo.getCustomerAge() + "','" + customerInfo.getCustomerPhone() + "','" + customerInfo.getArrivalStore() + "','" + DateTimeKit.now() + "') ";
            sqlMapper.insert(insertSql);
        } else {
            String updatesql = "update today_operation_info set operation_time='" + DateTimeKit.now() + "' where reservations_id='" + customerInfo.getReservationsId() + "' and " +
                    " left(operation_time,10)='" + DateTimeKit.now().substring(0, 10) + "' and operation_people='" + ShiroKit.getUser().getAccount() + "' " +
                    " and store='" + customerInfo.getArrivalStore() + "'";
            sqlMapper.update(updatesql);
        }
        //获取抵扣方式
        String checkoutSql = "select id,checkout_method from checkout_method_info where type in ('1','2')";
        List<CheckoutMethodInfo> checkoutMethodList = sqlMapper.selectList(checkoutSql, CheckoutMethodInfo.class);
        String checkoutMethodHtml = "";
        for (int i = 0; i < checkoutMethodList.size(); i++) {
            checkoutMethodHtml += "<option value='" + checkoutMethodList.get(i).getId() + "'>" + checkoutMethodList.get(i).getCheckoutMethod() + "</option>";
        }
        if (ShiroKit.getUser().getRefereeShipInfoList() == null) {
            String getListSql = "select id,referee_ship as refereeShip from referee_ship_info order by num asc;";
            List<RefereeShipInfo> refereeShipList = sqlMapper.selectList(getListSql, RefereeShipInfo.class);
            ShiroKit.getUser().setRefereeShipInfoList(refereeShipList);
        }
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        String jfbalancesql = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from return_cash_info where reservations_id='" + customerInfo.getReservationsId() + "'";
        ScoreDealInfo scoreDealInfo = sqlMapper.selectOne(jfbalancesql, ScoreDealInfo.class);
        BigDecimal b1 = new BigDecimal(Double.parseDouble(ShiroKit.getUser().getProportional()));
        BigDecimal b2 = new BigDecimal(Double.parseDouble(scoreDealInfo.getScoreBalance()));
        Double jfbalance = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        String selsql = "select reservations_id,members_num from members_user where reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(selsql, MembersUser.class);
        if (membersUser != null) {
            customerInfo.setMembersNum(membersUser.getMembersNum());
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
        model.addAttribute("checkoutMethodHtml", checkoutMethodHtml);
        model.addAttribute("custDealList", custDealList);
        model.addAttribute("payDealList", payDealList);
        model.addAttribute("arrearsDealList", arrearsDealList);
        model.addAttribute("totalServiceActualPay", totalServiceActualPay);
        model.addAttribute("totalArrears", totalArrears);
        model.addAttribute("totalPayDealActualPay", totalPayDealActualPay);
        model.addAttribute("totalPayDealArrears", totalPayDealArrears);
        model.addAttribute("totalArrearsAmount", totalArrearsAmount);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("roleName", ShiroKit.getUser().getRoleNames());
        model.addAttribute("roleNameLogin", ShiroKit.getUser().getRoleName());
        model.addAttribute("dealyesLogin", ShiroKit.getUser().getDealyes());
        model.addAttribute("payServiceInfoList", payServiceInfoList); //结账记录
        model.addAttribute("payServiceInfoList1", payServiceInfoList1);   //执行记录
        model.addAttribute("NoPayServiceInfoList", NoPayServiceInfoList); //未结账记录
        model.addAttribute("reservationsId", customerInfo.getReservationsId());
        model.addAttribute("customerId", customerInfo.getId());
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("customerInfoFirst", customerInfoFirst);  //首次到店患者信息
        model.addAttribute("recentlyCustomerStatus", customerPublicService.getNewCustomerStatus(customerInfo.getReservationsId()));
        model.addAttribute("getTime", getTime);
        model.addAttribute("consultantInfo", customerInfo);
        model.addAttribute("tabId", tabId);
        model.addAttribute("membersNum", customerInfo.getMembersNum());
        model.addAttribute("caseInfoList", caseInfoList);
        model.addAttribute("consultantInfoList", consultantInfoList); //看诊记录
        model.addAttribute("customerInfoList", customerInfoList);//就诊记录
        model.addAttribute("auditswitch", ShiroKit.getUser().getAuditswitch());
        model.addAttribute("jfbalance", jfbalance);
        model.addAttribute("khjfbalance", jfbalance);
        String jfbalancesql1 = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from score_deal where reservations_id='" + customerInfo.getReservationsId() + "'";
        ScoreDealInfo scoreDealInfo1 = sqlMapper.selectOne(jfbalancesql1, ScoreDealInfo.class);
        model.addAttribute("jfbalancea", scoreDealInfo1.getScoreBalance());
        String getMoneyBalance = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(getMoneyBalance, MembersUser.class);
        model.addAttribute("moneyBalance", membersUser1.getMoneyBalance());
        model.addAttribute("khmoneyBalance", membersUser1.getMoneyBalance());
        model.addAttribute("arrivalTimeStr", customerInfo.getArrivalTime());
        model.addAttribute("customerInfo1", customerInfo);
        model.addAttribute("treatmentUnit", customerInfo.getTreatmentUnit());
        model.addAttribute("isRefundAdmin", ShiroKit.getUser().getIsRefundAdmin());
        String vipLevelName = memberProductService.getVipLevelName(customerInfo.getReservationsId());
        model.addAttribute("vipLevelName", vipLevelName);
        String updasql = "update members_user set vip_level_name='" + vipLevelName + "' where reservations_id='" + customerInfo.getReservationsId() + "'";
        sqlMapper.update(updasql);
        return PREFIX + "customerDetail.html";
    }

    public List<PayServicedInfo> getDealInfoList(String operationTime, String reservationsId) throws Exception {
        if (ToolUtil.isEmpty(operationTime)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sqlresrvations = "select id from reservations_info where id='" + reservationsId + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlresrvations, ReservationsInfo.class);
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsInfo.getId() + "' and status=1 ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String dealTables = "";
        String rechargeTables = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsInfo.getId() + "' ";
                rechargeTables += "select * from " + head + "recharge_info where reservations_id='" + reservationsInfo.getId() + "' ";
            } else {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsInfo.getId() + "' union ";
                rechargeTables += "select * from " + head + "recharge_info where reservations_id='" + reservationsInfo.getId() + "' union ";
            }
        }
        String sql = "select t1.id as id,t1.outpatient_name as outpatientName,left(t1.get_time,19) as getTime,t1.is_do as isDo,t1.deal_status as dealStatus," +
                "t1.doctor1 as doctor,t1.nurse1 as nurse,t1.order_discount as orderDiscount,t1.deductionAmount as deductionAmount,t1.remarks as remarks,t1.serviceActualPay as serviceActualPay," +
                "t2.recharge_people as rechargePeople,t2.checkout_method as checkoutMethod," +
                "t2.document_number as documentNumber,t1.tc_name as tcName,left(t1.operation_time,19) as operationTime from (select t.id2 as id,t.outpatient_name as outpatient_name," +
                "t.get_time as get_time,t.tc_name as tc_name,t.is_do as is_do,t.deal_status as deal_status,GROUP_CONCAT(DISTINCT t.doctor) AS doctor1,GROUP_CONCAT(DISTINCT t.nurse) AS nurse1,(sum(t.service_actual_pay)+sum(t.deposit_amount)) as serviceActualPay," +
                "t.order_discount as order_discount,sum(t.deduction_amount) as deductionAmount,t.remarks as remarks,t.operation_time as operation_time from (" + dealTables + ") t where t.operation_time='" + operationTime + "' and t.reservations_id " +
                "= '" + reservationsId + "' and t.deal_status='已结账' group by t.get_time) t1 left join " + "(select b.recharge_people as recharge_people," +
                "b.document_number as  document_number,group_concat(distinct b.checkout_method) as checkout_method, b.operation_time as operation_time from (" + rechargeTables + ") b " +
                "group by b.operation_time) t2 on t1.get_time = t2.operation_time order by t1.get_time desc";
        List<PayServicedInfo> payServiceList = sqlMapper.selectList(sql, PayServicedInfo.class);
        return payServiceList;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Object list(SearchGuestRevisitInfo info, HttpServletRequest request) {
        Page<GuestRevisitInfo> page = new PageFactory<GuestRevisitInfo>().defaultPage();
        try {
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<GuestRevisitInfo> list = service.selectPageListByRevisit(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = service.selectPageListByRevisit(page, info);
            }
            page.setTotal(service.getQueryPagesRevisitCount(page, info));
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }
}